#!/bin/sh

# Stop all web launch daemons
/usr/sbin/hbanyware/stop_weblaunch

# Kill parent elxhbamgr
# If -n argument was passed to script, then don't kill the elxhbamgr
if [ "$1" != "-n" ]; then
  ppid=`ps -ea | grep elxhbamg | grep -v grep | awk '{ print $1 }' | sort -n | head -1`
  if [ ! -z "$ppid" ];then
        echo "Stopping HBAnyware HBA Management Server"
    kill $ppid > /dev/null 2>&1
    newppid="$ppid"
    trycount=0;
    while [ "$newppid" = "$ppid" ] && [ $trycount -lt  5 ]
    do
        sleep 1
        newppid=`ps -ea | grep elxhbamg | grep -v grep | awk '{ print $1 }' | sort -n | head -1`
        trycount=`expr $trycount + 1`
    done
  fi

  # Kill any remaining child of elxhbamgr
  for ppid in `ps -ea | grep elxhbamg | grep -v grep | awk '{ print $1 }' | sort -n`
  do
	kill -9 $ppid > /dev/null 2>&1
  done
fi

# Kill HBAnyware and SSC GUIs
# Get pid of script that started HBAnyware GUI
script_pid=`ps -eaf | grep hbanyware | grep "/bin/sh" | grep -v grep | head -1 | awk '{ print $2 }'`
#echo "script pid of hbanyware is $script_pid"
if [ "$script_pid" != "" ];then
    #  Get pid of GUI, child process of script_pid
    gui_pid=`ps -eaf | grep java | grep -v grep | grep "HBAnyware.jar" | awk '{ print $2 }'`
#    echo "guipid of hbanyware is $gui_pid"
    if [ "$gui_pid" != "" ];then
      echo "Stopping HBAnyware GUI"
      kill -9 $gui_pid > /dev/null 2>&1
    fi
fi

# Get pid of script that started SSC GUI
script_pid=`ps -eaf | grep ssc | grep "/bin/sh" | grep -v grep | head -1 | awk '{ print $2 }'`
if [ "$script_pid" != "" ];then
#  Get pid of GUI, child process of script_pid
   gui_pid=`ps -eaf | grep java | grep -v grep | grep "ssc.jar" | awk '{ print $2 }'`
   if [ "$gui_pid" != "" ];then
      echo "Stopping HBAnyware SSC GUI"
#     Kill HBAnyware SSC GUI
      kill -9 $gui_pid > /dev/null 2>&1
   fi
fi


# Kill parent elxdiscoveryd
ppid=`ps -ea | grep elxdisc | grep -v grep | awk '{ print $1 }' | sort -n | head -1`
if [ ! -z "$ppid" ];then
        echo "Stopping HBAnyware Discovery Server"
	kill $ppid > /dev/null 2>&1
fi

# Kill any remaining child of elxdisc
for ppid in `ps -ea | grep elxdisc | grep -v grep | awk '{ print $1 }' | sort -n`
do
	kill -9 $ppid > /dev/null 2>&1
done


